import '../models/user.dart';
import '../../../core/network/api_client.dart';

abstract class UserRepository {
  Future<List<User>> getUsers();
  Future<User> getUserById(int id);
}

class ApiUserRepository implements UserRepository {
  final ApiClient _apiClient = ApiClient();

  @override
  Future<List<User>> getUsers() async {
    try {
      final response = await _apiClient.get('/users');
      final List<dynamic> data = response.data;
      return data.map((json) => User.fromJson(json)).toList();
    } catch (e) {
      rethrow;
    }
  }

  @override
  Future<User> getUserById(int id) async {
    try {
      final response = await _apiClient.get('/users/$id');
      return User.fromJson(response.data);
    } catch (e) {
      rethrow;
    }
  }
}

class MockUserRepository implements UserRepository {
  @override
  Future<List<User>> getUsers() async {
    // 模拟网络延迟
    await Future.delayed(const Duration(seconds: 1));
    
    return [
      const User(
        id: 1,
        name: '张三',
        username: 'zhangsan',
        email: 'zhangsan@example.com',
        phone: '138-0000-0001',
        website: 'zhangsan.com',
        address: Address(
          street: '中山路',
          suite: '100号',
          city: '北京',
          zipcode: '100000',
          geo: Geo(lat: '39.9042', lng: '116.4074'),
        ),
        company: Company(
          name: '科技有限公司',
          catchPhrase: '创新驱动发展',
          bs: '软件开发',
        ),
      ),
      const User(
        id: 2,
        name: '李四',
        username: 'lisi',
        email: 'lisi@example.com',
        phone: '138-0000-0002',
        website: 'lisi.com',
        address: Address(
          street: '解放路',
          suite: '200号',
          city: '上海',
          zipcode: '200000',
          geo: Geo(lat: '31.2304', lng: '121.4737'),
        ),
        company: Company(
          name: '互联网公司',
          catchPhrase: '连接世界',
          bs: '平台服务',
        ),
      ),
    ];
  }

  @override
  Future<User> getUserById(int id) async {
    await Future.delayed(const Duration(milliseconds: 500));
    
    final users = await getUsers();
    return users.firstWhere(
      (user) => user.id == id,
      orElse: () => throw Exception('用户不存在'),
    );
  }
}